package com.jasonjan.jiance.module.me;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.jasonjan.jiance.R;
import com.jasonjan.jiance.api.ILoginApi;
import com.jasonjan.jiance.bean.LoginBean;
import com.jasonjan.jiance.global.Constant;
import com.jasonjan.jiance.global.ErrorAction;
import com.jasonjan.jiance.global.InitApp;
import com.jasonjan.jiance.global.RetrofitFactory;
import com.jasonjan.jiance.module.base.BaseActivity;
import com.jasonjan.jiance.util.MD5Util;
import com.jasonjan.jiance.util.T;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class LoginActivity extends BaseActivity {

    private static final String TAG = "LoginActivity";
    private String flag="";
    private EditText username_et;
    private EditText password_et;
    private Button login_btn;
    private String username;
    private String password;

    public static void launch(String flag) {
        InitApp.AppContext.startActivity(new Intent(InitApp.AppContext, LoginActivity.class)
                .putExtra("flag",flag)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle("登录");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        flag=getIntent().getStringExtra("flag");
        initView();
        initData();

    }

    private void initView(){
        username_et=(EditText) findViewById(R.id.username_et);
        password_et=(EditText) findViewById(R.id.password_et);
        login_btn=(Button) findViewById(R.id.login_btn);
    }

    private void initData(){
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                username=(username_et.getText()==null)?"":username_et.getText().toString().trim();
                password=(password_et.getText()==null)?"":password_et.getText().toString().trim();

                if(!username.equals("")&&!password.equals("")){
                    doRequest(username,password);
                }else{
                    T.showShort("用户名或密码不能为空！");
                }

            }
        });

    }

    private void doRequest(String username,String password){
        //构造请求参数
        JSONObject requestJson=new JSONObject();
        try{
            requestJson.put("account",username);
            requestJson.put("password", password);
            requestJson.put("sign",MD5Util.md5(Constant.salt+password));
        }catch (JSONException e){
            e.printStackTrace();
        }
        RequestBody body= RequestBody.create(MediaType.parse(Constant.Content_Type),requestJson.toString());
        RetrofitFactory.getRetrofit().create(ILoginApi.class).getLogin(body)
                .subscribeOn(Schedulers.io())
                .switchMap(new Function<LoginBean, Observable<LoginBean.ResultBean>>() {
                    @Override
                    public Observable<LoginBean.ResultBean> apply(@NonNull LoginBean loginBean) throws Exception {

                        LoginBean.ResultBean data = loginBean.getResult();
                        Log.d("login","data获取数据为："+data.toString());
                        return Observable.just(data);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<LoginBean.ResultBean>() {
                    @Override
                    public void accept(@NonNull LoginBean.ResultBean loginBean) throws Exception {
                        if(loginBean.getId()!=null&&!loginBean.getId().equals("")){
                            T.showShort("登录成功！");
                            SharedPreferences user_info=getSharedPreferences("user_info",Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor=user_info.edit();
                            editor.putBoolean("isLogin",true);
                            editor.putString("username",loginBean.getNickname());
                            editor.putString("token",loginBean.getToken());
                            editor.commit();
                            finish();
                        }else{
                            T.showShort("用户名或密码错误！");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        T.showShort("用户名或密码错误！");
                        ErrorAction.print(throwable);
                    }
                });
    }


    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (LoginActivity.this.getCurrentFocus() != null) {
                if (LoginActivity.this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(LoginActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }

}
